package life.mahu.community.controller;

import life.mahu.community.dto.FileDTO;
import life.mahu.community.provider.QQCloudProvider;
import life.mahu.community.util.Md5Util;
import life.mahu.community.util.VerifyCodeUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class FileController {

    @Value("${fileConfig.defaultPath}" + "/")
    private String savePath;//原图片文件夹

//    @Autowired
//    private QQCloudProvider qqCloudProvider;

    @RequestMapping("/editorImage/upload")
    @ResponseBody
    public FileDTO upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("editormd-image-file");
        try {
            //String fileName = uCloudProvider.upload(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
            String fileName=imageUpload(file);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            fileDTO.setUrl("/image/"+fileName);
            return fileDTO;
        } catch (Exception e) {
            log.error("upload error", e);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(0);
            fileDTO.setMessage("上传失败");
            return fileDTO;
        }
    }

//    @PostMapping("/image/upload")
//    @RequestMapping("/file/uploadEditor")
//    @ResponseBody
//    public FileDTO uploadEditor(HttpServletRequest request) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile file = multipartRequest.getFile("file");
//        List<String> urlList = new ArrayList<>();
//        try {
//            //String fileName = uCloudProvider.upload(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
//            String fileName=qqCloudProvider.upload(file);
//            FileDTO fileDTO = new FileDTO();
//            fileDTO.setErrno(0);
//            urlList.add(fileName);
//            fileDTO.setData(urlList);
//            fileDTO.setMessage("上传成功!");
//            return fileDTO;
//        } catch (Exception e) {
//            log.error("upload error", e);
//            FileDTO fileDTO = new FileDTO();
//            fileDTO.setErrno(100);
//            fileDTO.setMessage("上传失败");
//            return fileDTO;
//        }
//    }

    @GetMapping("/image/{hash}")
    @ResponseBody
    public byte[] getImage(@PathVariable("hash") String hash) throws IOException {
        if(!"default_head_image".equals(hash)&&!"hot".equals(hash)){
            // 在哈希码的前两位和后面其余位之间加/,从而实现储存的时候自己生成对应的文件夹来储存
            String fileHashPath = Md5Util.makePath(hash);
            File fileDir=new File(savePath + fileHashPath);
            if(fileDir.exists()) {//如果文件存在
                InputStream fis=new FileInputStream(fileDir);
                return FileCopyUtils.copyToByteArray(fis);
            }
            return null;
        }
        File fileDir=new File(savePath + hash);
        InputStream fis=new FileInputStream(fileDir);
        return FileCopyUtils.copyToByteArray(fis);
    }

    @PostMapping("/image/upload")
    @ResponseBody
    public String imageUpload(@RequestParam(name="file") MultipartFile file) throws IOException {
        // 获取文件的二进制数组
        byte[] fileByte = file.getBytes();
        // 将图片本身转化为32位哈希码,用于文件名来储存,防止文件重复
        String fileHash = Md5Util.md5HashCode32(fileByte);
        // 在哈希码的前两位和后面其余位之间加/,从而实现储存的时候自己生成对应的文件夹来储存
        String fileHashPath = Md5Util.makePath(fileHash);
        File fileDir=new File(savePath + fileHash.substring(0,2));
        if(!fileDir.exists())//如果头两个字母的文件夹不存在就新建一个
            fileDir.mkdir();
        // 将路径和文件名进行组合构建File对象
        File fileToSave = new File(savePath.concat(fileHashPath));
        if(!fileToSave.exists())//如果是新图片就保存
            FileCopyUtils.copy(fileByte, fileToSave);
        // 通过Spring的文件复制函数将二进制格式的文件复制到对应的路径下
        return fileHash;
    }


//    @RequestMapping("/file/uploadFile")
//    @ResponseBody
//    public FileDTO uploadFile(HttpServletRequest request) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile file = multipartRequest.getFile("file");
//        try {
//            //String fileName = uCloudProvider.upload(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
//            String fileName=qqCloudProvider.upload(file);
//            FileDTO fileDTO = new FileDTO();
//            fileDTO.setCode(0);
//            fileDTO.setUrl(fileName);
//            return fileDTO;
//        } catch (Exception e) {
//            log.error("upload error", e);
//            FileDTO fileDTO = new FileDTO();
//            fileDTO.setSuccess(1);
//            fileDTO.setMessage("上传失败");
//            return fileDTO;
//        }
//    }


    /**
     * 验证码
     * @param request
     * @param response
     */
    @SneakyThrows
    @GetMapping("/checkImg")
    public void checkImg(HttpServletRequest request, HttpServletResponse response){

        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //存入会话session
        HttpSession session = request.getSession();
        session.setAttribute("rand", verifyCode.toLowerCase());
        //生成图片
        int w = 100, h = 34;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

    }
}
